<template>
  <div class="container">
    <!-- 侧边栏 -->
    <div class="sidebar">
      <div class="logo">
        <h1>网络请求拦截器</h1>
        <p>设置与配置</p>
      </div>
      
      <nav class="nav-menu">
        <a 
          v-for="item in navItems" 
          :key="item.key"
          :href="`#${item.key}`" 
          :class="['nav-item', { active: activeSection === item.key }]"
          @click="setActiveSection(item.key)"
        >
          <span class="icon">{{ item.icon }}</span>
          {{ item.label }}
        </a>
      </nav>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 基本设置 -->
      <section v-show="activeSection === 'general'" class="content-section">
        <div class="section-header">
          <h2>基本设置</h2>
          <p>配置插件的基本功能和行为</p>
        </div>
        
        <div class="settings-group">
          <div class="setting-item">
            <div class="setting-info">
              <h3>启用插件</h3>
              <p>开启或关闭网络请求拦截功能</p>
            </div>
            <div class="setting-control">
              <el-switch v-model="settings.pluginEnabled"></el-switch>
            </div>
          </div>
          
          <div class="setting-item">
            <div class="setting-info">
              <h3>自动清理请求历史</h3>
              <p>自动清理超过指定天数的请求记录</p>
            </div>
            <div class="setting-control">
              <el-switch v-model="settings.autoCleanup"></el-switch>
              <el-select v-model="settings.cleanupDays" style="margin-left: 10px; width: 100px;">
                <el-option label="7天" :value="7"></el-option>
                <el-option label="14天" :value="14"></el-option>
                <el-option label="30天" :value="30"></el-option>
                <el-option label="90天" :value="90"></el-option>
              </el-select>
            </div>
          </div>
          
          <div class="setting-item">
            <div class="setting-info">
              <h3>最大请求记录数</h3>
              <p>限制保存的请求记录数量，避免占用过多内存</p>
            </div>
            <div class="setting-control">
              <el-input-number 
                v-model="settings.maxRequests" 
                :min="100" 
                :max="10000" 
                :step="100"
                style="width: 150px;"
              ></el-input-number>
            </div>
          </div>
          
          <div class="setting-item">
            <div class="setting-info">
              <h3>显示通知</h3>
              <p>当请求被Mock拦截时显示桌面通知</p>
            </div>
            <div class="setting-control">
              <el-switch v-model="settings.showNotifications"></el-switch>
            </div>
          </div>
        </div>
      </section>

      <!-- 域名白名单 -->
      <WhitelistPage v-show="activeSection === 'whitelist'" />

      <!-- Mock规则 -->
      <MockPage v-show="activeSection === 'mocks'" />

      <!-- 请求历史 -->
      <RequestPage v-show="activeSection === 'requests'" @create-mock-from-request="handleCreateMockFromRequest" />

      <!-- 存储记录 -->
      <StoragePage v-show="activeSection === 'storage'" />

      <!-- 导入导出 -->
      <section v-show="activeSection === 'import-export'" class="content-section">
        <div class="section-header">
          <h2>导入导出</h2>
          <p>备份和恢复插件配置数据</p>
        </div>
        
        <div class="import-export-manager">
          <div class="export-section">
            <h3>导出数据</h3>
            <p>将当前的配置和数据导出为JSON文件</p>
            <div class="export-options">
              <el-checkbox v-model="exportOptions.whitelist">域名白名单</el-checkbox>
              <el-checkbox v-model="exportOptions.mocks">Mock规则</el-checkbox>
              <el-checkbox v-model="exportOptions.requests">请求历史</el-checkbox>
              <el-checkbox v-model="exportOptions.settings">插件设置</el-checkbox>
            </div>
            <el-button type="primary" @click="exportData">导出数据</el-button>
          </div>
          
          <div class="import-section">
            <h3>导入数据</h3>
            <p>从JSON文件导入配置和数据</p>
            <div class="import-area">
              <el-upload
                :auto-upload="false"
                :on-change="handleFileChange"
                :show-file-list="false"
                accept=".json"
              >
                <el-button type="primary">选择文件导入</el-button>
              </el-upload>
            </div>
          </div>
        </div>
      </section>

      <!-- 关于 -->
      <section v-show="activeSection === 'about'" class="content-section">
        <div class="section-header">
          <h2>关于插件</h2>
          <p>插件信息和使用说明</p>
        </div>
        
        <div class="about-content">
          <div class="plugin-info">
            <h3>网络请求拦截器</h3>
            <p class="version">版本 1.0.0</p>
            <p class="description">
              这是一个强大的浏览器插件，用于拦截和模拟网络请求。
              支持域名白名单、Mock数据管理、请求监控等功能。
            </p>
          </div>
          
          <div class="features">
            <h4>主要功能</h4>
            <ul>
              <li>🌐 域名白名单管理 - 精确控制拦截范围</li>
              <li>🎭 Mock数据管理 - 灵活的API模拟</li>
              <li>📊 请求监控 - 详细的请求分析</li>
              <li>💾 数据导入导出 - 便捷的配置备份</li>
              <li>⚙️ 灵活配置 - 个性化设置选项</li>
            </ul>
          </div>
          
          <!-- 支付宝打赏 -->
          <div class="donation-section">
            <h4>【请作者喝咖啡】</h4>
            <div class="alipay-qr">
              <el-image :src="alipayicon"
                        :preview-src-list="[alipayicon]"
                        alt="支付宝二维码" class="qr-code" />
              <p class="donation-text">如果这个插件对您有帮助，欢迎请作者喝杯咖啡 ☕</p>
            </div>
          </div>
        </div>
      </section>
    </div>

 
  </div>
</template>

<script>
import alipayicon from '../../assets/alipay.jpg'
import { getStorage, setStorage } from '../../utils/chrome'
import StoragePage from './components/StoragePage.vue'
import MockPage from './components/MockPage.vue'
import RequestPage from './components/RequestPage.vue'
import WhitelistPage from './components/WhitelistPage.vue'

export default {
  name: 'OptionsApp',
  components: {
    StoragePage,
    MockPage,
    RequestPage,
    WhitelistPage
  },
  data() {
    return {
      alipayicon,
      activeSection: 'general',
      navItems: [
        { key: 'general', label: '基本设置', icon: '⚙️' },
        { key: 'whitelist', label: '域名白名单', icon: '🌐' },
        { key: 'mocks', label: 'Mock规则', icon: '🎭' },
        { key: 'requests', label: '请求历史', icon: '📊' },
        { key: 'storage', label: '存储记录', icon: '🗄️' },
        { key: 'import-export', label: '导入导出', icon: '💾' },
        { key: 'about', label: '关于', icon: 'ℹ️' }
      ],
      settings: {
        pluginEnabled: true,
        autoCleanup: true,
        cleanupDays: 30,
        maxRequests: 1000,
        showNotifications: false
      },

      exportOptions: {
        whitelist: true,
        mocks: true,
        requests: false,
        settings: true
      }
    }
  },

  mounted() {
    this.loadData()
  },
  methods: {
    setActiveSection(section) {
      this.activeSection = section
    },
    
    // 数据加载
    async loadData() {
      try {
        // 模拟加载数据，实际应该从Chrome存储中加载
        this.loadSettings()
      } catch (error) {
        console.error('加载数据失败:', error)
      }
    },
    
    async loadSettings() {
      // 从Chrome存储加载设置
      const saved = await getStorage('interceptor-settings')
      if (saved && saved['interceptor-settings']) {
        this.settings = { ...this.settings, ...saved['interceptor-settings'] }
      }
    },
    

    
    // 处理从RequestPage传递的创建Mock事件
    handleCreateMockFromRequest(request) {
      // 切换到Mock规则页面
      this.activeSection = 'mocks'
      // 这里可以进一步处理，比如预填充Mock表单
      this.$message.success('已切换到Mock规则页面')
    },
    
    // 导入导出
    async exportData() {
      const data = {}
      if (this.exportOptions.whitelist) {
        // 从Chrome存储获取whitelist
        const whitelistData = await getStorage('whitelist')
        data.whitelist = whitelistData?.whitelist || []
      }
      if (this.exportOptions.mocks) {
        // 从Chrome存储获取mockList
        const mockData = await getStorage('mockList')
        data.mockList = mockData?.mockList || []
      }
      if (this.exportOptions.requests) {
        // 从Chrome存储获取requestList
        const requestData = await getStorage('requestList')
        data.requestList = requestData?.requestList || []
      }
      if (this.exportOptions.settings) data.settings = this.settings
      
      const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = 'interceptor-data.json'
      a.click()
      URL.revokeObjectURL(url)
      
      this.$message.success('数据导出成功')
    },
    
    handleFileChange(file) {
      const reader = new FileReader()
      reader.onload = async (e) => {
        try {
          const data = JSON.parse(e.target.result)
          if (data.whitelist) await setStorage({ whitelist: data.whitelist })
          if (data.mockList) await setStorage({ mockList: data.mockList })
          if (data.requestList) await setStorage({ requestList: data.requestList })
          if (data.settings) {
            this.settings = { ...this.settings, ...data.settings }
            await setStorage({ 'interceptor-settings': this.settings })
          }
          
          this.$message.success('数据导入成功')
        } catch (error) {
          this.$message.error('文件格式错误')
        }
      }
      reader.readAsText(file.raw)
    }
  },
  
  watch: {
    settings: {
      async handler() {
        await setStorage({ 'interceptor-settings': this.settings })
      },
      deep: true
    }
  }
}
</script>

<style>
/* 导入原有的CSS样式 */
@import url('../../assets/options.css');

/* Vue特定的样式调整 */
.el-switch {
  margin-left: 10px;
}

/* 支付宝打赏样式 */
.donation-section {
  margin-top: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 12px;
  text-align: center;
  border: 2px solid #e1e8ed;
}

.donation-section h4 {
  color: #1890ff;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  text-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.alipay-qr {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.qr-code {
  width: 150px;
  height: 150px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  transition: transform 0.3s ease;
}

.qr-code:hover {
  transform: scale(1.05);
}

.donation-text {
  color: #666;
  font-size: 14px;
  margin: 0;
  font-style: italic;
}

</style>